# -*- coding: utf-8 -*-

import os

from django.db import models
import django.utils.timezone as timezone
from django.db.models.signals import post_delete
from django.dispatch import receiver
from product.models import Chipset
from user.models import Group
from mysite import settings

CATEGORY = ( 
    ("应用笔记", "应用笔记"),  
    ("设计参考", "设计参考"),
)
  
  
class Hardware(models.Model):
    '''硬件信息
    
    '''
    title = models.CharField("标题", max_length=100)
    display = models.BooleanField("用户可见", default=True)
    guest = models.BooleanField("访客可见", default=False)
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name="分组", blank=True, null=True)
    number = models.CharField("编号", max_length=30, null=True, blank=True)
    category = models.CharField("类型", max_length=20, choices=CATEGORY, default="", null=True, blank=True)
    chip = models.ManyToManyField(Chipset, verbose_name="芯片", default="", null=True, blank=True)
    format = models.CharField("格式", max_length=50, null=True, blank=True)
    version = models.CharField("版本", max_length=50, null=True, blank=True)
    file = models.FileField("上传文件", upload_to='upload/doc/', null=True, blank=True, help_text="")
    #description = models.CharField("描述", max_length=200, null=True, blank=True, help_text="限200个字符")
    description = models.TextField("描述", max_length=250, null=True, blank=True, help_text="限250个字符")
    #date = models.DateTimeField("发布日期", auto_now_add=True)
    date = models.DateTimeField("发布日期", default=timezone.now)

    class Meta:
        verbose_name = "硬件信息"
        verbose_name_plural = verbose_name
        ordering = ['title', 'version', 'date']

    def __str__(self):
        return self.title
    
    
## 添加监听器
@receiver(post_delete, sender=Hardware)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'file')
    #rint(str(files))
    if not files:
        return
    fname = os.path.join(settings.MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)

    
    
    

 

    
    